package com.solomon.travel.common.web.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.solomon.travel.common.base.controller.BaseController;
import com.solomon.travel.common.model.ApiResponse;
import com.solomon.travel.common.model.Page;
import com.solomon.travel.common.po.User;
import com.solomon.travel.common.service.UserService;
import com.solomon.travel.common.util.ConstantUtils;
import com.solomon.travel.common.util.IdUtils;
import com.solomon.travel.common.util.PageUtils;

@RestController
@RequestMapping("/web/user")
public class UserController extends BaseController{
	@Resource
	private UserService userService;
	
	@RequestMapping("/add")
	public ApiResponse add(HttpServletRequest request, User user)throws Exception{
		User admin = currentUser();
		if (!admin.getType().equals(0)) {
			return new ApiResponse(201, "你没有权限添加用户");
		}
		if (userService.getByUsername(user.getUsername()) != null) {
			return new ApiResponse(202, "用户名已存在");
		}
		user.setObjectId(IdUtils.uuid());
		user.setCreatedAt(new Date());
		userService.registe(user);
		return new ApiResponse(ConstantUtils.RESPONSE_CODE_OK);
	}
	
	@RequestMapping("/list")
	public ApiResponse listUser(Integer type,Page page) throws Exception{
		int counts = userService.countByType(type);
		page = PageUtils.createPage(page, counts);
		List<User> users = userService.listByType(type, page);
		HashMap<String, Object> result = new HashMap<>();
		result.put("users", users);
		result.put("page", page);
		return new ApiResponse(ConstantUtils.RESPONSE_CODE_OK,result);
	}
	
	@RequestMapping("/update")
	public ApiResponse update(User user) {
		userService.update(user);
		return defaultResponse();
	}
	
	@RequestMapping("/disable")
	public ApiResponse disable(User user) {
		user.setStatus(0);
		userService.update(user);
		return defaultResponse();
	}
	
	@RequestMapping("/enable")
	public ApiResponse enable(User user) {
		user.setStatus(1);
		userService.update(user);
		return defaultResponse();
	}
	
	@RequestMapping("/detail")
	public ApiResponse detail(String userId) {
		return new ApiResponse(ConstantUtils.RESPONSE_CODE_OK, userService.get(userId));
	}
}
